package com.elitetyc.eliteim.server;

import com.elitetyc.eliteim.server.config.IMServerProperties;
import com.elitetyc.eliteim.server.handler.ServeChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description netty服务端
 * @Date 2021/9/15 17:47
 */
@Component
@Slf4j
public class EliteIMServer {

    @Autowired
    private IMServerProperties imServerProperties;

    @Autowired
    private ServeChannelInitializer serveChannelInitializer;

    private final EventLoopGroup boosGroup = new NioEventLoopGroup();
    private final EventLoopGroup workGroup = new NioEventLoopGroup();

    @PostConstruct
    public void init() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(boosGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(imServerProperties.getPort()))
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(serveChannelInitializer);
        final ChannelFuture channelFuture = bootstrap.bind().sync();
        if (channelFuture.isSuccess()){
            log.info("im server start success!!");
        }
    }

    @PreDestroy
    public void destroy(){
        boosGroup.shutdownGracefully().syncUninterruptibly();
        workGroup.shutdownGracefully().syncUninterruptibly();
        log.info("close im server success!!");
    }

}
